/**
 * Copyright 2016-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inmorn.extspring.hessian;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.remoting.caucho.HessianServiceExporter;

import com.inmorn.extspring.util.StringUtils;

public class ExtHessianServiceExporter extends HessianServiceExporter {

    /**
     * hessian验证器，如果hessian服务端需要验证，需要自定义改验证器
     */
    private IHessianValidator hessianValidator;

    @Override
    public void handleRequest(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {

		Logger logger = LoggerFactory.getLogger(getClass());
	
		if (hessianValidator != null) {
		    String queryString = request.getQueryString();
		    Map<String, String> queryMap = this.getQueryMap(queryString);
		    if (!hessianValidator.validate(queryMap)) {
			logger.error("hessian auth faid, queryString:" + queryString);
			throw new HessianException("hessian auth faid");
		    }
		}
	
		super.handleRequest(request, response);
    }

    private Map<String, String> getQueryMap(String queryString) {
	Map<String, String> queryMap = new HashMap<String, String>();
	if (StringUtils.isEmpty(queryString)) {
	    logger.error("heesion validate param is empty");
	} else {
	    String[] queryArray = queryString.split("&");
	    for (String s : queryArray) {
		if (s.indexOf("=") > 0) {
		    String keys[] = s.split("=");

		    if (keys.length == 2) {
			queryMap.put(keys[0], keys[1]);
		    }
		}
	    }
	}
	return queryMap;

    }

    public IHessianValidator getHessianValidator() {
	return hessianValidator;
    }

    public void setHessianValidator(IHessianValidator hessianValidator) {
	this.hessianValidator = hessianValidator;
    }

}
